<template>
  <nav
    class="aui-navbar"
    :class="`aui-navbar--${$store.state.navbarLayoutType}`"
  >
    <div class="aui-navbar__header">
      <h1 class="aui-navbar__brand" @click="$router.push({ name: 'home' })">
        <a class="aui-navbar__brand-lg" href="javascript:;">{{
          $t("brand.lgt")
        }}</a>
        <a class="aui-navbar__brand-mini" href="javascript:;">{{
          $t("brand.minit")
        }}</a>
      </h1>
    </div>
    <div class="aui-navbar__body">
      <el-menu class="aui-navbar__menu mr-auto" mode="horizontal">
        <el-menu-item
          index="1"
          @click="$store.state.sidebarFold = !$store.state.sidebarFold"
        >
          <svg
            class="icon-svg aui-navbar__icon-menu aui-navbar__icon-menu--switch"
            aria-hidden="true"
          >
            <use xlink:href="#icon-outdent"></use>
          </svg>
        </el-menu-item>
        <!-- 多民宿切换 -->

        <el-menu-item
          index="2"
          class="aui-navbar__avatar"
          v-if="$store.state.user.type == '1' && homestayIdArr.length > 0"
        >
          <el-dropdown placement="bottom" :show-timeout="0">
            <span class="el-dropdown-link">
              <span>{{ $store.state.user.homestayName }}</span>
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="setHomeId(item)"
                v-for="(item, index) in homestayIdArr"
                :key="index"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
        <!-- 多商户切换 -->
        <el-menu-item
          index="2"
          class="aui-navbar__avatar"
          v-if="$store.state.user.type == '2'"
        >
          <el-dropdown placement="bottom" :show-timeout="0">
            <span class="el-dropdown-link">
              <span>{{ $store.state.user.MerchantName }}</span>
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="setMerchantId(item)"
                v-for="(item, index) in MerchantIdArr"
                :key="index"
                >{{ item.name }}({{
                  $getDictLabel("MerchantCategory", item.merchantCategory)
                }})</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
      <el-menu class="aui-navbar__menu" mode="horizontal">
        <el-menu-item index="2" @click="refresh()">
          <svg
            class="icon-svg aui-navbar__icon-menu aui-navbar__icon-menu--refresh"
            aria-hidden="true"
          >
            <use xlink:href="#icon-sync"></use>
          </svg>
        </el-menu-item>
        <el-menu-item index="4" v-if="$hasPermission('sys:notice:all')">
          <el-badge :is-dot="messageTip">
            <a href="#" @click="myNoticeRouter()"
              ><i class="el-icon-bell"></i
            ></a>
          </el-badge>
        </el-menu-item>
        <el-menu-item index="3" @click="fullscreenHandle()">
          <svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true">
            <use xlink:href="#icon-fullscreen"></use>
          </svg>
        </el-menu-item>
        <el-menu-item index="4" class="aui-navbar__avatar">
          <el-dropdown placement="bottom" :show-timeout="0">
            <span class="el-dropdown-link">
              <img src="~@/assets/img/avatar.png" />
              <span>{{ $store.state.user.realName }}</span>
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="updatePasswordHandle()">{{
                $t("updatePassword.title")
              }}</el-dropdown-item>
              <el-dropdown-item @click.native="logoutHandle()">{{
                $t("logout")
              }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 弹窗, 修改密码 -->
    <update-password
      v-if="updatePasswordVisible"
      ref="updatePassword"
    ></update-password>
  </nav>
</template>

<script>
import { messages } from "@/i18n";
import screenfull from "screenfull";
import UpdatePassword from "./main-navbar-update-password";
import { clearLoginInfo } from "@/utils";
import { isURL } from "@/utils/validate";
export default {
  inject: ["refresh"],
  data() {
    return {
      homestayIdArr: [],
      MerchantIdArr: [],
      i18nMessages: messages,
      updatePasswordVisible: false,
      messageTip: false,
      naList: [],
      permissionsList: [],
    };
  },
  components: {
    UpdatePassword,
  },
  mounted() {
    // this.$nextTick(() => {
    setTimeout(() => {
      this.homestayIdArr = this.$store.state.user.homestayIdArr;
      this.MerchantIdArr = this.$store.state.user.MerchantIdArr;
      this.navList = JSON.parse(localStorage.getItem("navListArr"));
      this.permissionsList = JSON.parse(
        localStorage.getItem("permissionsListArr")
      );
      this.$forceUpdate();
    }, 2000);

    // })
    // 未读通知数
    //this.getUnReadCount()
  },
  methods: {
    fnAddDynamicMenuRoutes(menuList = [], routes = []) {
      var temp = [];
      for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
          temp = temp.concat(menuList[i].children);
          continue;
        }
        // 组装路由
        var route = {
          path: "",
          component: null,
          name: "",
          meta: {
            ...window.SITE_CONFIG["contentTabDefault"],
            menuId: menuList[i].id,
            title: menuList[i].name,
          },
        };
        // eslint-disable-next-line
        let URL = (menuList[i].url || "").replace(/{{([^}}]+)?}}/g, (s1, s2) =>
          eval(s2)
        ); // URL支持{{ window.xxx }}占位符变量
        if (isURL(URL)) {
          route["path"] = route["name"] = `i-${menuList[i].id}`;
          route["meta"]["iframeURL"] = URL;
        } else {
          URL = URL.replace(/^\//, "").replace(/_/g, "-");
          route["path"] = route["name"] = URL.replace(/\//g, "-");
          route["component"] = () => import(`@/views/modules/${URL}`);
        }
        routes.push(route);
        this.show = true;
      }
      if (temp.length >= 1) {
        return this.fnAddDynamicMenuRoutes(temp, routes);
      }
      const moduleRoutes = {
        path: "/",
        component: () => import("@/views/main"),
        name: "main",
        redirect: { name: "home" },
        meta: { title: "主入口布局" },
        children: [
          {
            path: "/home",
            component: () => import("@/views/modules/home"),
            name: "home",
            meta: { title: "首页", isTab: true },
          },
          {
            path: "/iframe",
            component: null,
            name: "iframe",
            meta: { title: "iframe", isTab: true },
          },
          {
            path: "/priceSetList",
            component: () => import("@/views/modules/roomManage/priceSetList"),
            name: "priceSetList",
            meta: { title: "批量定价" },
          },
           {
            path: "/roomShape-concatLink",
            component: () => import("@/views/modules/roomManage/roomShape-concatLink"),
            name: "roomShape-concatLink",
            meta: { title: "携程房型映射" },
          },
        ],
      };
      // 添加路由
      this.$router.addRoutes([
        {
          ...moduleRoutes,
          name: "main-dynamic-menu",
          children: routes,
        },
        { path: "*", redirect: { name: "404" } },
      ]);
      window.SITE_CONFIG["dynamicMenuRoutes"] = routes;
      window.SITE_CONFIG["dynamicMenuRoutesHasAdded"] = true;
    },
    setHomeId(item) {
      if (item.name == this.$store.state.user.homestayName) {
        return;
      }
      this.$store.state.user.homestayId = item.id || "";
      this.$store.state.user.homestayName = item.name || "";
      //切换时更改菜单和权限并缓存
      if (this.navList[item.id]) {
        window.SITE_CONFIG["menuList"] = this.navList[item.id];
      } else {
        window.SITE_CONFIG["menuList"] = this.navList[-1];
      }
      if (this.permissionsList[item.id]) {
        window.SITE_CONFIG["permissions"] = this.permissionsList[item.id];
      } else {
        window.SITE_CONFIG["permissions"] = this.permissionsList[-1];
      }
      localStorage.setItem(
        "currentMenuList",
        JSON.stringify(window.SITE_CONFIG["menuList"])
      );
      localStorage.setItem(
        "currentPermissions",
        JSON.stringify(window.SITE_CONFIG["permissions"])
      );
      this.fnAddDynamicMenuRoutes(window.SITE_CONFIG["menuList"]);
      localStorage.setItem("MerchantId", this.$store.state.user.homestayId); //财务报表用
      localStorage.setItem("homestayId", this.$store.state.user.homestayId);
      localStorage.setItem("homestayName", this.$store.state.user.homestayName);
      localStorage.setItem("ss_merchantCategory", item.merchantCategory || "");
      this.refresh();
    },
    setMerchantId(item) {
      if (item.name == this.$store.state.user.MerchantName) {
        return;
      }
      this.$store.state.user.MerchantId = item.id || "";
      this.$store.state.user.MerchantName = item.name || "";
      if (this.navList[item.id]) {
        window.SITE_CONFIG["menuList"] = this.navList[item.id];
      } else {
        window.SITE_CONFIG["menuList"] = this.navList[-1];
      }
      if (this.permissionsList[item.id]) {
        window.SITE_CONFIG["permissions"] = this.permissionsList[item.id];
      } else {
        window.SITE_CONFIG["permissions"] = this.permissionsList[-1];
      }
      localStorage.setItem(
        "currentMenuList",
        JSON.stringify(window.SITE_CONFIG["menuList"])
      );
      localStorage.setItem(
        "currentPermissions",
        JSON.stringify(window.SITE_CONFIG["permissions"])
      );
      this.fnAddDynamicMenuRoutes(window.SITE_CONFIG["menuList"]);
      localStorage.setItem("MerchantId", this.$store.state.user.MerchantId); //财务报表用
      localStorage.setItem("homestayId", this.$store.state.user.MerchantId);
      localStorage.setItem("homestayName", this.$store.state.user.MerchantName);
      localStorage.setItem("ss_merchantCategory", item.merchantCategory || "");
      this.refresh();
    },
    myNoticeRouter() {
      this.$router.replace("sys-notice-user");
    },
    getUnReadCount() {
      this.$http
        .get(`/sys/notice/mynotice/unread`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          if (res.data > 0) {
            this.messageTip = true;
          }
        })
        .catch(() => {});
    },
    // 全屏
    fullscreenHandle() {
      if (!screenfull.enabled) {
        return this.$message({
          message: this.$t("fullscreen.prompt"),
          type: "warning",
          duration: 500,
        });
      }
      screenfull.toggle();
    },
    // 修改密码
    updatePasswordHandle() {
      this.updatePasswordVisible = true;
      this.$nextTick(() => {
        this.$refs.updatePassword.init();
      });
    },
    userClear() {
      localStorage.setItem("homestayId", "");
      localStorage.setItem("homestayName", "");
      localStorage.setItem("homestayIdArr", []);
      localStorage.setItem("MerchantId", "");
      localStorage.setItem("MerchantName", "");
      localStorage.setItem("MerchantIdArr", []);
      localStorage.setItem("ss_merchantCategory", "");
      localStorage.setItem("currentMenuList", "");
      localStorage.setItem("currentPermissions", "");
      this.$store.state.user.homestayIdArr = [];
      this.$store.state.user.MerchantIdArr = [];
    },
    // 退出
    logoutHandle() {
      this.$confirm(
        this.$t("prompt.info", {
          handle: this.$t("logout"),
        }),
        this.$t("prompt.title"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$http
            .post("/auth/oauth/logout")
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              clearLoginInfo();
              this.userClear();
              this.$router.push({
                name: "login",
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
};
</script>
